package com.bankcomm.ui;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.bankcomm.BankcommApplication;
import com.bankcomm.R;
import com.bankcomm.common.LPMid;
import com.bankcomm.ui.show.MyScrollLayout;
import com.bankcomm.ui.show.OnViewChangeListener;
import com.bankcomm.ui.views.DBManager;
import com.bankcomm.ui.views.DataStorage;
import com.bankcomm.util.LPUtils;
import com.rytong.tools.datastorage.PackageManagerAndroid;
import com.rytong.tools.utils.CacheBitmapUtils;
import com.rytong.tools.utils.EventHandler;
import com.rytong.tools.utils.Utils;

/**
 * 闪屏界面
 * 
 * @author zhaobin
 * 
 * @date 2013.5.13
 */
public class SplashScreenActivity extends BaseViewCopy implements OnViewChangeListener{

	private LPMid mid_;
	public String reply = null;
	private ImageView splashImage;
	public Thread thread_;
	public static boolean isrun = true;

	/**
	 * 判断是否是首次使用应用程，进入引导页面 add by cheng 2013.12.14
	 */
	//private boolean isShowSwitch = false;

	public MyScrollLayout mScrollLayout;
	private ImageView[] mImageViews;
	private int mViewCount;
	private int mCurSel;

	private boolean isInitFinished = false;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		LPUtils.CalculateScreenSize(this);
		initObject(this);
		initObjectForApp();
		//将计算本地图片宽度前移，供多处调用add by zhaobin
		LPUtils.getLocalImage((Context)this);
		
		handleJarEvent();
		// 判断是否可以进入引导页面
//		String showSwitch = PackageManagerAndroid.ANDROIDDB.get("isswitchshow");
//		if (null == showSwitch || "".equalsIgnoreCase(showSwitch)) {
//			setContentView(R.layout.swichview);
//			initSwitchView();
//			isShowSwitch = true;
//			PackageManagerAndroid.ANDROIDDB.save("isswitchshow","isswitchshow");
//		}else{
//			isShowSwitch = false;
		setContentView(R.layout.splashscreen_act_layout);
		initSplashView();			
//		}

		/**
		 * 拷贝数据库文件至/data/data/com.bankcomm/目录中， 主要是大学生版本中使用到
		 */
		Utils.SCHOOL_IMAGE_PATH = Utils.getActivity().getFilesDir().getPath().concat("/")+ "school/";
		mid_.db = new DBManager(this).openDatabase();
		
		startApp();
		//gotoEMPView("mytest.xml");
	}

	/**
	 * 初始化视图view
	 */
	private void initSplashView() {
		splashImage = (ImageView) findViewById(R.id.imgtwo);
	}

	/**
	 * 初始化引导页面
	 */
	private void initSwitchView() {
		mScrollLayout = (MyScrollLayout) findViewById(R.id.ScrollLayout);

		LinearLayout linearLayout = (LinearLayout) findViewById(R.id.llayout);

		mViewCount = mScrollLayout.getChildCount();
		mImageViews = new ImageView[mViewCount];

		AssetManager am = getAssets();  
		String name = null;
		for (int i = 0; i < mViewCount; i++) {
			name = "bcm_show_"+(i+1)+".jpg";
			Drawable drawable;
			try {
				drawable = new BitmapDrawable(CacheBitmapUtils.getBitmap(CacheBitmapUtils.readStream(am.open(name))));
				((ImageView)mScrollLayout.getChildAt(i)).setImageDrawable(drawable);
				System.gc();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			mImageViews[i] = (ImageView) linearLayout.getChildAt(i);
			mImageViews[i].setEnabled(true);
			mImageViews[i].setTag(i);
			mImageViews[i].setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					int pos = (Integer) (v.getTag());
					setCurPoint(pos);
					mScrollLayout.snapToScreen(pos);
				}
			});
		}

		mCurSel = 0;
		mImageViews[mCurSel].setEnabled(false);
		mScrollLayout.SetOnViewChangeListener(this);
	}

	/**
	 * 初始化框架相关的参数
	 */
	void initObjectForApp() {
		Utils.calculateScreenSize(this);
		mid_ = new LPMid(this);
		try {
			mid_.initLightPoleApp(this);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 程序启动
	 */
	private void startApp(){
		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				// 初始化离线资源
				initAppData();
			}
		}, 100);
	}
	
	/**
	 * 初始化Handler
	 */
	private void handleJarEvent() {
		EventHandler uhandler = new EventHandler();
		uhandler.eventHandler = new Handler() {
			public void handleMessage(Message msg) {
				if (null != msg && msg.what == EventHandler.MSG_GOTOALLOWACT) {
					gotoMainView();
				} else if (null != msg
						&& msg.what == EventHandler.MSG_KILL_PROCESS) {
					exitSystem();
				} else if (null != msg
						&& msg.what == EventHandler.MSG_SPLASH_STARTCONTROLBAR) {
					// firstrun = true ;
				}
			}
		};
	}

	/**
	 * 初始化数据
	 */
	private void initAppData() {
		Thread thread = new Thread() {
			@Override
			public void run() {
				super.run();
				// 解压本地离线资源文件
				mid_.um_.unzipLocalOfflineResources();
				LPMid.getInstance().um_.data = new DataStorage(SplashScreenActivity.this, null);
				isInitFinished = true;
				handler.sendEmptyMessage(1000);
			}
		};
		thread.start();
	}

	/**
	 * 跳转到EMPView,主要是调试本地页面用的
	 * 
	 * @param name
	 */
	public void gotoEMPView(String name) {
		String reply = Utils.getStringFormAsset(this, name);
		Intent intent = new Intent();
		intent.setClass(this, EMPView.class);
		intent.putExtra("reply", reply);
		startActivity(intent);
		this.finish();
	}

	/**
	 * 跳转到首页面
	 * */
	public void gotoMainView() {
		if (null != reply && !reply.equals("")) {
			new Thread(new Runnable() {
				@Override
				public void run() {
				}
			}).start();
		}
	}

	/**
	 * 重置contentview
	 */
	public void resetContentView(){
		this.setContentView(R.layout.splashscreen_act_layout);
		initSplashView();
		//isShowSwitch = false;
		if(isInitFinished){
			handler.sendEmptyMessage(1000);
		}
	}
	
	/**
	 * 移动进度条
	 */
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1000:
//				if(!isShowSwitch){
//					// 跳转到首页
//					goMainHome();
//				}
				String showSwitch = PackageManagerAndroid.ANDROIDDB.get("isswitchshow");
				if (null == showSwitch || "".equalsIgnoreCase(showSwitch)) {
					setContentView(R.layout.swichview);
					initSwitchView();
					PackageManagerAndroid.ANDROIDDB.save("isswitchshow","isswitchshow");
				}else{
					goMainHome();
				}
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 进入首页
	 */
	public void goMainHome(){
		Intent intent = new Intent();
		intent.setClass(SplashScreenActivity.this,BOCMainHome.class);
		startActivity(intent);
		finish();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exitWithConfirm();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void setCurPoint(int index) {
		if (index < 0 || index > mViewCount - 1 || mCurSel == index) {
			return;
		}

		mImageViews[mCurSel].setEnabled(true);
		mImageViews[index].setEnabled(false);

		mCurSel = index;
	}
	@Override
	public void OnViewChange(int position) {
		// TODO Auto-generated method stub
		setCurPoint(position);
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Utils.releaseObject(splashImage);
		if (null != thread_) {
			thread_.interrupt();
			thread_ = null;
		}
		
		try{
			if(null != mScrollLayout && null != mImageViews){
				int size = mScrollLayout.getChildCount();
				for(int i = 0 ;i < size;i++){
					ImageView view = (ImageView) mScrollLayout.getChildAt(i);
					Utils.releaseObject(view);
					Utils.releaseObject(mImageViews[i]);
					System.gc();
				}
				mScrollLayout = null;
				System.gc();
			}
		}catch(RuntimeException e){
			e.printStackTrace();
		}
		BankcommApplication.getInstance().removeActivity(this);
	}
}
